# -*-Shell-script-*-
# ecmfunctions - ecmctl utility functions
# This file contains functions to be used by ecm modules
# Copyright (c) 2003 by Clunix Inc. All Rights Reserved.
#

# Ouput utility
echo_success () { echo -e "$*\\033[60G[  \\033[1;32mOK\\033[0;39m  ]"; }
echo_failure () { echo -e "$*\\033[60G[\\033[1;31mFAILED\\033[0;39m]"; }

# A complicated function to stop a program. within 12 sec
ecmkillproc() {
    pid=$1
    # check if the process is not running (returns failure)
    if [ ! -d "/proc/$pid" ]; then return 1; fi
    # send SIGTERM and check if process exits
    kill -TERM $pid; usleep 100000
    if [ ! -d "/proc/$pid" ]; then return 0; fi
    usleep 300000
    if [ ! -d "/proc/$pid" ]; then return 0; fi
    usleep 600000
    if [ ! -d "/proc/$pid" ]; then return 0; fi
    # now 1 sec delayed; try other SIGTERMs
    kill -TERM $pid; sleep 1
    if [ ! -d "/proc/$pid" ]; then return 0; fi
    kill -TERM $pid; sleep 2
    if [ ! -d "/proc/$pid" ]; then return 0; fi
    kill -TERM $pid; sleep 4 
    if [ ! -d "/proc/$pid" ]; then return 0; fi
    # now 8 sec delayed; try SIGKILL
    kill -KILL $pid; sleep 1 
    if [ ! -d "/proc/$pid" ]; then return 0; fi
    sleep 3
    if [ ! -d "/proc/$pid" ]; then return 0; fi
    # oh my god! total 10 sec delayed and even SIGKILL is not working; orz
    # just give up and returns failure
    return 1;
}

function start_daemon() {
    prog=$1
    shift 1
    args=$*

    echo -n "Starting $prog: "

    if [ -n "`/sbin/pidof $prog`" ]; then
	echo_failure "(already running)"
	return 1;
    fi

    bin/$prog $args
    ret=$?
    if [ $ret -eq 0 ]; then
	echo_success
    else
	echo_failure
    fi
    return $ret
}

function stop_daemon() {
    prog=$1
    pidfile=$CLX_HOME/log/$prog.pid

    echo -n "Shutting down $prog: "

    # clear up garbage pid file
    if [ -e $pidfile ];  then
        if [ ! -d "/proc/`cat $pidfile`" ]; then
            rm -f $pidfile;
        fi
    fi

    if [ -e $pidfile ]; then
	ecmkillproc "`cat $pidfile`" \
        && echo_success || echo_failure
    elif [ -n "`/sbin/pidof $prog`" ]; then
	ecmkillproc "`/sbin/pidof $prog`" \
        && echo_success "(no pid file)" || echo_failure "(no pid file)"
    else
    	echo_failure "(not running)"
    fi
}

function status_daemon() {
    prog=$1
    pidfile=$CLX_HOME/log/$prog.pid

    if [ -e $pidfile ] && [ -d /proc/`cat $pidfile` ]; then
	echo "$prog is running (pid=`cat $pidfile`)"
    elif [ -z "`/sbin/pidof $prog`" ]; then
	echo "$prog is stopped"
    else
        echo "$prog is running (pid=`/sbin/pidof $prog`) (no pid file)"
    fi
}


